package com.elitel.frame.main.config.serviceaccess.interceptor;

import com.elitel.common.utils.SpringUtils;
import com.elitel.frame.base.service.BaseQueryfieldService;
import com.elitel.frame.base.service.SysPrjServiceService;
import com.elitel.frame.main.config.serviceaccess.util.ServiceAccessPrintWriterUtil;
import com.elitel.frame.main.entity.SysPrjservice;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.elitel.common.core.constant.RequestConstant.SERVICE_ID;

/**
 * 服务状态拦截器
 *
 * @author hi_bj
 * @since 2023-10-17
 */

public class ParamRequireInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        SysPrjServiceService sysPrjServiceService = SpringUtils.getBean(SysPrjServiceService.class);
        SysPrjservice sysPrjservice = sysPrjServiceService.getSysPrjserviceByServiceCode(request.getParameter(SERVICE_ID));
        // 查询必填字段
        BaseQueryfieldService bean = SpringUtils.getBean(BaseQueryfieldService.class);
        Set<String> requiredFields = bean.selectRequiredFieldsByServiceGuid(sysPrjservice.getGuid());
        StringBuilder msg = new StringBuilder();
        if (!ObjectUtils.isEmpty(requiredFields)) {
            // 获取请求参数
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (String requiredField : requiredFields) {
                String[] values = parameterMap.get(requiredField);
                if (values == null) {
                    msg.append("参数:").append(requiredField).append("不能为空;");
                    continue;
                }
                List<String> collect = Arrays.stream(values).filter(StringUtils::isNotBlank).collect(Collectors.toList());
                String parameterVal = request.getParameter(requiredField);
                if (ObjectUtils.isEmpty(collect) && StringUtils.isBlank(parameterVal)) {
                    msg.append("参数:").append(requiredField).append("不能为空;");
                }
            }
        }
        if (msg.length() > 0) {
            ServiceAccessPrintWriterUtil.write(response, msg.toString());
            return false;
        }
        return true;
    }
}
